package com.atguigu.msmservice.contrller;

import com.atguigu.commonutils.R;
import com.atguigu.msmservice.service.MsmService;
import com.atguigu.msmservice.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("edumsm")
@CrossOrigin
public class MsmApiController {

    @Autowired
    private MsmService msmService;

    //短信验证码，5min内有效
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //发送短信
    @GetMapping("/send/{phone}")
    public R  sendMSM(@PathVariable String phone)
    {
        //如果redis有值就不发送
        String codeRedis = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(codeRedis))
        {
            return  R.ok();
        }

        //生成随机值，传递阿里云进行发送
        String code = RandomUtil.getSixBitRandom();
        HashMap<String,Object> param=new HashMap<>();
        param.put("code",code);

        //调用service进行短信发送
        boolean isSend=msmService.send(param,phone);
        if(isSend) {
            //发送成功，放入redis,然后
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return R.ok().message("发送短信成功");
        }else{
            return R.error().message("发送短信失败");
        }
    }
}
